package com.agileai.miscdp.hotweb.ui.actions.treecontent;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;

import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.progress.IProgressService;

import com.agileai.miscdp.DeveloperConst;
import com.agileai.miscdp.hotweb.database.DBManager;
import com.agileai.miscdp.hotweb.database.SqlBuilder;
import com.agileai.miscdp.hotweb.domain.Column;
import com.agileai.miscdp.hotweb.domain.ListTabColumn;
import com.agileai.miscdp.hotweb.domain.PageFormField;
import com.agileai.miscdp.hotweb.domain.PageParameter;
import com.agileai.miscdp.hotweb.domain.ProjectConfig;
import com.agileai.miscdp.hotweb.domain.treecontent.ContentTableInfo;
import com.agileai.miscdp.hotweb.domain.treecontent.TreeContentFuncModel;
import com.agileai.miscdp.hotweb.ui.actions.BaseInitGridAction;
import com.agileai.miscdp.hotweb.ui.editors.treecontent.TACBasicConfigPage;
import com.agileai.miscdp.hotweb.ui.editors.treecontent.TACContentEditDialog;
import com.agileai.miscdp.hotweb.ui.editors.treecontent.TACContentListArea;
import com.agileai.miscdp.hotweb.ui.editors.treecontent.TreeContentModelEditor;
import com.agileai.miscdp.hotweb.ui.editors.treecontent.TreeContentModelEditorContributor;
import com.agileai.miscdp.util.DialogUtil;
import com.agileai.miscdp.util.MiscdpUtil;
import com.agileai.util.StringUtil;
/**
 * 初始化表中功能模型数据
 */
public class TACInitGridAction extends BaseInitGridAction{
	private String tableName;
	private TACBasicConfigPage basicConfigPage;
	
	
	public TACInitGridAction() {
	}
	
	public void setContributor(TreeContentModelEditorContributor contributor) {
		this.contributor = contributor;
	}
	
	public void run() {
		IWorkbenchPage workbenchPage = contributor.getPage();
		IEditorPart editorPart = workbenchPage.getActiveEditor();
		modelEditor = (TreeContentModelEditor)editorPart;
		this.basicConfigPage = ((TreeContentModelEditor)modelEditor).getBasicConfigPage(); 
		Combo tableNameCombo = basicConfigPage.getTableNameCombo();
		String tableName = tableNameCombo.getText();
		Shell shell = modelEditor.getSite().getShell();
		if (StringUtil.isNullOrEmpty(tableName)){
			DialogUtil.showMessage(shell,"消息提示","请选择主表!",DialogUtil.MESSAGE_TYPE.WARN);
			return;
		}
		TreeContentFuncModel funcModel = ((TreeContentModelEditor)modelEditor).getFuncModel();
		if (funcModel.getContentTableInfoList().isEmpty()){
			DialogUtil.showMessage(shell,"消息提示","请至少选择一个关联表!",DialogUtil.MESSAGE_TYPE.WARN);
			return;
		}
		
		String projectName = funcModel.getProjectName();
		this.tableName = tableNameCombo.getText();
		String[] primaryKeys = DBManager.getInstance(projectName).getPrimaryKeys(tableName);
		if (primaryKeys == null ){
			MessageDialog.openInformation(shell, "消息提示","所选择的数据表没有主键!");
			return;
		}
		if (StringUtil.isNullOrEmpty(basicConfigPage.getFuncSubPkgText().getText())){
			DialogUtil.showMessage(shell,"消息提示","目录编码不能为空!",DialogUtil.MESSAGE_TYPE.WARN);
			return;
		}
		if (StringUtil.isNullOrEmpty(basicConfigPage.getColumnIdFieldText().getText())){
			DialogUtil.showMessage(shell,"消息提示","节点ID字段不能为空!",DialogUtil.MESSAGE_TYPE.WARN);
			return;
		}
		if (StringUtil.isNullOrEmpty(basicConfigPage.getColumnNameFieldText().getText())){
			DialogUtil.showMessage(shell,"消息提示","节点名称字段不能为空!",DialogUtil.MESSAGE_TYPE.WARN);
			return;
		}
		if (StringUtil.isNullOrEmpty(basicConfigPage.getColumnParentIdFieldText().getText())){
			DialogUtil.showMessage(shell,"消息提示","父节点ID字段不能为空!",DialogUtil.MESSAGE_TYPE.WARN);
			return;
		}
		if (StringUtil.isNullOrEmpty(basicConfigPage.getColumnSortFieldText().getText())){
			DialogUtil.showMessage(shell,"消息提示","节点排序字段不能为空!",DialogUtil.MESSAGE_TYPE.WARN);
			return;
		}		
		
		boolean doInitGrid = MessageDialog.openConfirm(shell,"消息提示","自动填写可能会覆盖已有内容，是否继续!");
		if (!doInitGrid){
			return;
		}
		((TreeContentModelEditor)modelEditor).getBasicConfigPage().getExtendAttribute().refreshTemplateCombo((TreeContentModelEditor)modelEditor);		
		((TreeContentModelEditor)modelEditor).getContentsCfgPage().refreshContentConfig();
		
        IProgressService progressService = PlatformUI.getWorkbench().getProgressService();
        IRunnableWithProgress runnable = new IRunnableWithProgress() {
			public void run(IProgressMonitor monitor) throws InvocationTargetException {
				try {
					doRun(monitor);
				} catch (Exception e) {
					throw new InvocationTargetException(e);
				} finally {
					monitor.done();
				}
			}
        };
        try {
			progressService.runInUI(PlatformUI.getWorkbench().getProgressService(),
					runnable,ResourcesPlugin.getWorkspace().getRoot());
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
	public void doRun(IProgressMonitor monitor) {
		monitor.beginTask("init grid values....", 1000);
		monitor.subTask("init basic values....");
		monitor.worked(50);
		((TreeContentModelEditor)modelEditor).buildFuncModel();
		TreeContentFuncModel funcModel = ((TreeContentModelEditor)modelEditor).getFuncModel();
		try {
			funcModel.setTreeTableName(tableName);
			String namePrefix = MiscdpUtil.getValidName(tableName)+"8Content";
			String beanIdPrefix = namePrefix.substring(0,1).toLowerCase()+namePrefix.substring(1,namePrefix.length());
			
			String funcBasePath = this.basicConfigPage.getFuncSubPkgText().getText();
			funcModel.setFuncSubPkg(funcBasePath);
			
			funcModel.setListJspName(funcBasePath +"/"+namePrefix+"List.jsp");
			funcModel.setServiceId(beanIdPrefix+"ManageService");
			
			String projectName = funcModel.getProjectName();
			ProjectConfig projectConfig = new ProjectConfig();
			String configFile = MiscdpUtil.getCfgFileName(projectName,DeveloperConst.PROJECT_CFG_NAME);
			projectConfig.setConfigFile(configFile);
			projectConfig.initConfig();
			String mainPkg = projectConfig.getMainPkg();
			funcModel.setImplClassName(mainPkg +".bizmoduler."+funcBasePath+"."+namePrefix +"ManageImpl");
			funcModel.setInterfaceName(mainPkg +".bizmoduler."+funcBasePath+"."+namePrefix+"Manage");
			
			monitor.subTask("init form grid values....");
			monitor.worked(800);

			DBManager dbManager = DBManager.getInstance(projectName);
			boolean isManageTree = ((TreeContentModelEditor)modelEditor).getBasicConfigPage().getIsManageTreeY().getSelection();
			Column[] columns = dbManager.getColumns(tableName);
			if (isManageTree){
				funcModel.getTreeEditFormFields().clear();
				List<String> hiddenFields = new ArrayList<String>();
				hiddenFields.add(funcModel.getColumnParentIdField());
				hiddenFields.add(funcModel.getColumnSortField());
				TreeContentFuncModel.initPageFormFields(columns, funcModel.getTreeEditFormFields(), hiddenFields);

				TableViewer tableViewer = ((TreeContentModelEditor)modelEditor).getContentsCfgPage().getTreeEditArea().getTableViewer();
				tableViewer.setInput(funcModel.getTreeEditFormFields());
				tableViewer.refresh();
			}
			
			List<ContentTableInfo> contentTableInfos = funcModel.getContentTableInfoList();
			List<TACContentListArea> taContentListAreas = ((TreeContentModelEditor)modelEditor).getContentsCfgPage().getTaContentListAreas();
			for (int i=0;i < contentTableInfos.size();i++){
				ContentTableInfo contentTableInfo = contentTableInfos.get(i);
				String tabId = contentTableInfo.getTabId();
				List<ListTabColumn> listTabColumns = funcModel.getContentListTableColumnsMap().get(tabId);
				if (listTabColumns != null){
					listTabColumns.clear();					
				}else{
					listTabColumns = new ArrayList<ListTabColumn>();
					funcModel.getContentListTableColumnsMap().put(tabId, listTabColumns);
				}
				
				String contentTableName = contentTableInfo.getTableName();
				columns = dbManager.getColumns(contentTableName);
				initListTableColumns(columns,listTabColumns,contentTableInfo);
				
				TACContentListArea contentListArea = taContentListAreas.get(i);
				TableViewer columnTableViewer = contentListArea.getColumnTableViewer();
				columnTableViewer.setInput(listTabColumns);
				columnTableViewer.refresh();
				
				List<PageParameter> pageParameters = funcModel.getContentPageParametersMap().get(tabId);
				if (pageParameters != null){
					pageParameters.clear();					
				}else{
					pageParameters = new ArrayList<PageParameter>();
					funcModel.getContentPageParametersMap().put(tabId, pageParameters);
				}
				TableViewer pageParamTableViewer = contentListArea.getPageParamTableViewer();
				pageParamTableViewer.setInput(pageParameters);
				pageParamTableViewer.refresh();
				
				String listSql = this.buildListSql(contentTableInfo,tableName);
				contentTableInfo.setQueryListSql(listSql);
				contentTableInfo.setTabName(contentTableInfo.getTableName());
				contentListArea.initValues();
				
				List<PageFormField> contentEditFormFields = funcModel.getContentEditFormFieldsMap().get(tabId);
				if (contentEditFormFields != null){
					contentEditFormFields.clear();	
				}else{
					contentEditFormFields = new ArrayList<PageFormField>();
					funcModel.getContentEditFormFieldsMap().put(tabId, contentEditFormFields);
				}
				String foreignKey = null;
				String tableMode = contentTableInfo.getTableMode();
				if (ContentTableInfo.TableMode.One2Many.equals(tableMode)){
					foreignKey = contentTableInfo.getColField();
				}
				
				List<String> hiddenFields = new ArrayList<String>();
				hiddenFields.add(foreignKey);
				TreeContentFuncModel.initPageFormFields(columns, contentEditFormFields, hiddenFields);
				
				TACContentEditDialog contentEditDialog = contentListArea.getContentEditDialog();
				TableViewer contentEditViewer = contentEditDialog.getTableViewer();
				if (contentEditViewer != null){
					contentEditViewer.setInput(contentEditFormFields);
					contentEditViewer.refresh();					
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		modelEditor.initValues();
		
		monitor.subTask("refresh viewer....");
		monitor.worked(900);
		
		return;
	}
	
	private String buildListSql(ContentTableInfo contentTableInfo,String treeTableName){
		String result = null;
		String tableMode = contentTableInfo.getTableMode();
		String contentTableName = contentTableInfo.getTableName();
		SqlBuilder sqlBuilder = new SqlBuilder();
		
		TreeContentFuncModel funcModel = ((TreeContentModelEditor)modelEditor).getFuncModel();
		String projectName = funcModel.getProjectName();
		
		DBManager dbManager = DBManager.getInstance(projectName);
		String[] treePrimaryKeys = dbManager.getPrimaryKeys(treeTableName);
		String masterKey = treePrimaryKeys[0];
		String[] contentColumns = MiscdpUtil.getColNames(dbManager, contentTableName);
		if (ContentTableInfo.TableMode.One2Many.equals(tableMode)){
			String colField = contentTableInfo.getColField();
			result = sqlBuilder.findRecordsByForeignKeySql(contentTableName, contentColumns, colField);
		}else{
			String relTableName = contentTableInfo.getRelTableName();
			String[] contentPrimaryKeys = dbManager.getPrimaryKeys(contentTableName);
			String contentPrimaryKey = contentPrimaryKeys[0];
			result = sqlBuilder.findRecordsMany2ManySql(treeTableName, contentTableName, relTableName, contentColumns, masterKey, contentPrimaryKey);
		}
		return result;
	}
	
	public void initListTableColumns(Column[] columns,List<ListTabColumn> listTableColumns,ContentTableInfo contentTableInfo){
		for (int i=0;i < columns.length;i++){
			if (columns[i].isPK()){
				if (contentTableInfo != null){
					contentTableInfo.setPrimaryKey(columns[i].getName());
				}
				continue;
			}
			if (contentTableInfo != null){
				if(columns[i].getName().equals(contentTableInfo.getColField())){
					continue;
				}
			}
			ListTabColumn listTabColumn = new ListTabColumn();
			listTabColumn.setProperty(columns[i].getName());
			listTabColumn.setTitle(columns[i].getLabel());
			listTabColumn.setWidth("100");
			listTabColumn.setCell(MiscdpUtil.getDataType(columns[i].getClassName()));
			if ("java.sql.Timestamp".equals(columns[i].getClassName())){
				listTabColumn.setFormat("yyyy-MM-dd HH:mm");				
			}
			else if ("java.sql.Date".equals(columns[i].getClassName())){
				listTabColumn.setFormat("yyyy-MM-dd");
			}
			listTableColumns.add(listTabColumn);				
		}
	}
}